<template>
  <div class="container">
    <div style="margin-bottom: 20px;">提示：若Excel包含图片，请优先使用PNG/JPG格式，并保存为XLSX文件</div>
    <div class="top-controls">
      <input type="file" @change="handleFileUpload" accept=".xlsx" />
    </div>
    <div class="main-content">
      <div class="left-panel">
        <el-form v-model="formObj">
          <el-form-item label="文档标题">
            <el-input v-model="formObj.label" placeholder="请输入文档标题"></el-input>
            <el-button @click="handleJump('label')">跳转</el-button>
          </el-form-item>
          <el-form-item label="文档描述">
            <el-input v-model="formObj.description" placeholder="请输入文档描述"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="right-panel">
        <el-button @click="exportToWord">导出</el-button>
        <el-button @click="insertData">插入变量数据</el-button>
        <el-button @click="handleSwitch">替换</el-button>
        <div id="luckysheet" style="width: 100%; height: 600px;"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,onMounted, nextTick, watch, unref, reactive, inject, onUnmounted } from 'vue';
import { ElTree, ElEmpty, ElButton,
  ElIcon, ElMessage, ElMessageBox, ElForm, ElFormItem, ElInput} from 'element-plus';
import 'element-plus/dist/index.css';
import * as Excel from 'exceljs'
import { exportExcel } from 'luckytool';


const treeData = ref([
  
])
const treeProps = {
  label: 'label',
  children: 'children',
  isLeaf: 'isLeaf' 
}
const formObj = reactive({
  label: '安彦辉',
  description: '安达维尔',
});
const labelMap = {
  label: '文档标题',
  description: '文档描述',
}

onMounted(() => {
  console.log('jQuery 是否可用:', !!$);
});

let luckysheetfiles = ''
let excelTitle = ''
let luckyWorkbook = ''
const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  if (!file) return;
  try {
    // 增强EMF图片解析错误处理
    // enhanceEMFParser();
    LuckyExcel.transformExcelToLucky(file, function(exportJson, luckysheetfile){
    //Get the worksheet data after conversion
      luckysheetfiles = luckysheetfile
      excelTitle = exportJson.info.name.split('.xlsx')[0]
      luckyWorkbook = luckysheet.create({
        container: 'luckysheet', // luckysheet is the container id
        data:exportJson.sheets,
        title:exportJson.info.name,
        userInfo:exportJson.info.name.creator,
        lang: 'zh', // 设置语言为中文，
        // plugins: ['chart', 'filter', 'pivot', 'image'] // 确保包含 'image' 插件
      });
      
    });
  } catch (error) {
    console.error('Error enhancing EMF parser:', error);
  }
  
};
const exportToWord = () => {
  // const luckysheetfile = luckysheet.getluckysheetfile()
  // exportSheetExcel(luckysheetfile, excelTitle)
  exportExcel(luckysheet, excelTitle , Excel ).then((res) => {
    // console.log("result==>", res);
    ElMessage.success("导出成功")
}).catch((err) => {});
}
const insertData = () => {
  // 获取当前活动工作表
  const selectedRange = luckysheet.getRange()
  if (selectedRange && selectedRange.length > 0) {
    const startRow = selectedRange[0].row[0]; // 起始行
    const startCol = selectedRange[0].column[0]; // 起始列

    luckysheet.setCellValue(startRow, startCol,formObj.label); // 插入数据到指定位置
    luckysheet.refresh();
  }
}
const handleNodeClick = (data, node, event) => {
  console.log(data, node, event);
};
const append = (data) => {
  const newData = { id: data.id + 1, label: '新节点', level: data.level + 1 };
  treeData.value.push(newData);
};
const handleSwitch = () => {
  luckysheet.replace(formObj.label, 'Andawell')
}
// 跳转到制定的位置
let clickNum = 0;
let oldLabel = '';
const handleJump = (label) => {
  // luckysheet.setRangeFilter('open')
  // luckysheet.openSearchDialog()
  // document.getElementById('luckysheet-search-replace').style.display = 'block'
  // const search = document.querySelector('#luckysheet-icon-seachmore')
  // search.click()
  // const searchItem = document.querySelector('.luckysheet-cols-menuitem[itemvalue=search]')
  // searchItem.click()
  // const searchInput = document.querySelector('#searchInput .formulaInputFocus')
  // searchInput.value = formObj[label]
  // const searchBtn = document.querySelector('#searchNextBtn')
  // searchBtn.click()
  // 处理切换字段的逻辑
  if (oldLabel !== label) {
    oldLabel = label;
    clickNum = 0;
  }
  const cellDatas = luckysheet.find(formObj[label])
  if (cellDatas.length === 0) {
    return; 
  } else if (clickNum > cellDatas.length - 1) {
    clickNum = 0;
    ElMessage.warning("没有更多数据了")
    return; 
  } else {
    clickNum++;
    // const linkNode = cellDatas[clickNum - 1];
    const { row, column } = cellDatas[clickNum - 1];
    luckysheet.setRangeShow({
      row: [row, row],
      column: [column, column],
    });
    let scrollData = {
      targetRow: row,
      targetColumn: 0
    }
    if (column > 16) {
      scrollData = {
        targetRow: row,
        targetColumn: column - 10,
      }
    }
    luckysheet.scroll(scrollData);
    // linkNode.scrollIntoView({ behavior: 'smooth', block: 'top' });
  }
}
onUnmounted(() => {
 luckysheet.destroy() 
})
</script>

<style>
.top-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.export-btn {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.export-btn:hover {
  background: #0056b3;
  text-decoration: none;
}

.container {
  padding: 20px;
}

.main-content {
  display: flex;
  margin-top: 20px;
  gap: 20px;
}

.left-panel {
  flex: 1;
  max-width: 300px;
  border-right: 1px solid #ccc;
  padding-right: 20px;
}

.right-panel {
  flex: 3;
}

button {
  background: none;
  border: none;
  text-align: left;
  cursor: pointer;
  color: #007bff;
  margin: 5px 0;
}

button:hover {
  text-decoration: underline;
}
.luckysheet-share-logo {
  display: none; 
}
</style>